import { createServer } from 'http'

const 消息头 = {
  CORS: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Max-Age': 30 * 86400
  },
  SSE: 请求 => ({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    ...(请求.httpVersionMajor === 1 && { 'Connection': 'keep-alive' })
  })
}
const 端口 = 3000

const 服务器 = createServer()
服务器.listen(端口)
服务器.on('error', e => { console.error(e); process.exit(1) })
服务器.on('listening', () => console.log('HTTP 服务器已启动（监听于', 服务器.address(), '）'))
/**
 * (method) Server<typeof IncomingMessage, typeof ServerResponse>.on(
 *            event: "request", listener: RequestListener<typeof IncomingMessage, typeof ServerResponse>
 *          ): Server<typeof IncomingMessage, typeof ServerResponse> (+10 overloads)
 */
服务器.on('request', (请求, 响应) => {
  if (请求.url === '/' + encodeURIComponent('前端消息接入点')) {
    响应.writeHead(200, { ...消息头.SSE(请求), ...消息头.CORS })
    if (服务器.设定发信函数) {
      服务器.设定发信函数(消息文本 => 响应.write(`data:${消息文本}\nid:${Date.now()}\n\n`))
      delete 服务器.设定发信函数
    }
    if (请求.method === 'POST') {
      let body = []
      请求.on('error', (err) => {
        console.error(err)
      }).on('data', (chunk) => {
        body.push(chunk)
        console.log(Buffer.concat(body).toString())
      }).on('end', () => {
        body = Buffer.concat(body).toString()
        console.log('【完结】')
      })
    }
    return
  }
})

export const 服务器发信 = new Promise(_ => 服务器.设定发信函数 = _) 